/*
 * Copyright (c) 2018-2999 北京小象智慧信息科技有限公司 All rights reserved.
 *
 * https://www.xiaoxiangai.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.api.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.yami.shop.bean.model.ExtensionWorker;
import com.yami.shop.bean.model.PhoneNumberParm;
import com.yami.shop.bean.model.Yqm;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.CacheManagerUtil;
import com.yami.shop.common.util.Json;
import com.yami.shop.dao.YqmMapper;
import com.yami.shop.security.enums.App;
import com.yami.shop.security.model.AppConnect;
import com.yami.shop.security.service.AppConnectService;
import com.yami.shop.security.service.YamiUser;
import com.yami.shop.security.service.YamiUserDetailsService;
import com.yami.shop.security.util.SecurityUtils;
import com.yami.shop.service.ExtensionService;
import lombok.AllArgsConstructor;
import org.apache.ibatis.annotations.Param;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import com.yami.shop.bean.app.dto.UserDto;
import com.yami.shop.bean.app.param.UserInfoParam;
import com.yami.shop.bean.model.User;
import com.yami.shop.service.UserService;

import cn.hutool.extra.emoji.EmojiUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ma.glasnost.orika.MapperFacade;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.Date;

@RestController
@RequestMapping("/p/user")
@Api(tags="用户接口")
@AllArgsConstructor
public class UserController {
	private static String yqmSuccess ="000";//填写邀请码成功

	private static String  yqmError ="111";//邀请码不能和上级相互绑定

	private static String yqmError1 ="222";//不能绑定自己的邀请码

	private static String yqmErrpr2 ="333";//邀请码输入错误

	private final UserService userService;

	private final MapperFacade mapperFacade;

	private final CacheManagerUtil cacheManagerUtil;

	@Autowired
	private AppConnectService appConnectService;

	@Autowired
	private YqmMapper yqmMapper;

	private final ExtensionService extensionService;

    /**
     * 查看用户接口
     */
    @GetMapping("/userInfo")
    @ApiOperation(value="查看用户信息", notes="根据用户ID（userId）获取用户信息")
    public ResponseEntity<UserDto> userInfo() {
    	String userId = SecurityUtils.getUser().getUserId();
    	User user = userService.getById(userId);
    	UserDto userDto = mapperFacade.map(user, UserDto.class);
        return ResponseEntity.ok(userDto);
    }

    @PutMapping("/setUserInfo")
    @ApiOperation(value="设置用户信息", notes="设置用户信息")
    public ResponseEntity<Void> setUserInfo(@RequestBody UserInfoParam userInfoParam) {
    	String userId = SecurityUtils.getUser().getUserId();
    	User user = new User();
    	user.setUserId(userId);
    	user.setPic(userInfoParam.getAvatarUrl());
    	user.setNickName(EmojiUtil.toAlias(userInfoParam.getNickName()));
    	userService.updateById(user);
		String cacheKey = App.MINI.value() + StrUtil.COLON + SecurityUtils.getUser().getBizUserId();
		cacheManagerUtil.evictCache("yami_user", cacheKey);
        return ResponseEntity.ok(null);
    }

    @PutMapping("/setPuserid")
	@ApiOperation(value = "绑定上级用户",notes = "绑定上级用户")
	public ResponseEntity<String> setPuserid(@RequestBody User user){
		String result = null;
    	String userId = SecurityUtils.getUser().getUserId();
		User cuser = userService.getUserByUserId(userId);
		//先去用户表中查询有没有用户填入的邀请码
		User puser = userService.getUserByYqm(user.getYqm());
		//绑定上级用户,并向邀请码表中插入一条数据
		if(puser!=null){
			  if(!puser.getUserId().equals(cuser.getUserId())) {
				 if(!puser.getPuserid().equals(cuser.getUserId())){
					 cuser.setYqm(user.getYqm());
					 cuser.setPuserid(puser.getUserId());
					 result = userService.setyqmLog(cuser);
					 return ResponseEntity.ok(result);
				 }else{
					 return ResponseEntity.ok(yqmError);
				 }
			  }else{
				     return  ResponseEntity.ok(yqmError1);
			  }
		}else{
			return ResponseEntity.ok(yqmErrpr2);
		}
	}

	@GetMapping("/getYqm")
	@ApiOperation(value = "获取当前用户的邀请码",notes = "获取当前用户的邀请码")
	public ResponseEntity<Boolean> getYqm(){
    	boolean bl =false;
		//查询当前用户有没有绑定邀请码
		String userId = SecurityUtils.getUser().getUserId();
		Yqm yqm = yqmMapper.getYqmByUserid(userId);
		if(yqm!=null){
				bl = true;
				return  ResponseEntity.ok(bl);
		}
    	return  ResponseEntity.ok(bl);
	}

	//获取手机号码
	@GetMapping("/getPhoneNumber")
	public ResponseEntity<String> mini_getPhone(String encryptedData,String iv)
	{
		String  sessionKey = null;
		//获取当前用户的sessionKey的值
		String bizUserid = SecurityUtils.getUser().getBizUserId();
		if(null!=bizUserid){
		AppConnect appConnect = appConnectService.getAppConncetByBizUserId(bizUserid);
			if(appConnect!=null){
				 sessionKey =	appConnect.getSessionKey();
			}
		}
		String obj=getPhoneNumber(sessionKey,encryptedData,iv);//解密电话号码
		PhoneNumberParm phoneNumberParm = Json.parseObject(obj,PhoneNumberParm.class);
		//获取手机号码
		String phoneNumber = phoneNumberParm.getPhoneNumber();
		YamiUser yamiUser = SecurityUtils.getUser();
		//保存手机号码
		if(yamiUser!=null) {
			User user = userService.getUserByUserId(yamiUser.getUserId());
			user.setUserMobile(phoneNumber);
			userService.updateById(user);
		}

		return ResponseEntity.ok(phoneNumber);

	}

	//解析电话号码
	public String getPhoneNumber(String session_key, String encryptedData, String iv) {
		byte[] dataByte = Base64.decode(encryptedData);

		byte[] keyByte = Base64.decode(session_key);

		byte[] ivByte = Base64.decode(iv);
		try {

			int base = 16;
			if (keyByte.length % base != 0) {
				int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
				byte[] temp = new byte[groups * base];
				Arrays.fill(temp, (byte) 0);
				System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
				keyByte = temp;
			}
			// 初始化
			Security.addProvider(new BouncyCastleProvider());
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
			AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
			parameters.init(new IvParameterSpec(ivByte));
			cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
			byte[] resultByte = cipher.doFinal(dataByte);
			if (null != resultByte && resultByte.length > 0) {
				String result = new String(resultByte, "UTF-8");
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}

	/**
	 * 解析获取unionid
	 */
	@GetMapping("/getUnionid")
	public ResponseEntity<String> mini_getUnionid(String encryptedData,String iv)
	{
		String  sessionKey = null;
		//获取当前用户的sessionKey的值
		String bizUserid = SecurityUtils.getUser().getBizUserId();
		AppConnect appConnect = null;
		if(null!=bizUserid){
			 appConnect = appConnectService.getAppConncetByBizUserId(bizUserid);
			if(appConnect!=null){
				sessionKey = appConnect.getSessionKey();
			}
		}
		String obj=getPhoneNumber(sessionKey,encryptedData,iv);//解密电话号码
		UserInfoParam userInfoParam = Json.parseObject(obj,UserInfoParam.class);
		//获取unionId
		String unionId = userInfoParam.getUnionId();
		//保存unionId
		appConnect.setBizUnionid(unionId);
		appConnectService.saveOrUpdate(appConnect);
		return ResponseEntity.ok(unionId);

	}


	/**
	 * 推广员申请
	 */
	@PostMapping("/extensionWorker")
	public ResponseEntity<String> extensionWorker(){
		String result ="success";
		String userId = SecurityUtils.getUser().getUserId();
		User user = userService.getUserByUserId(userId);
		//查询申请是否已有申请记录
		ExtensionWorker worker = extensionService.getExtensionWorker(userId);
		if(worker==null){
			ExtensionWorker extensionWorker = new ExtensionWorker();
			extensionWorker.setPic(user.getPic());
			extensionWorker.setNickName(user.getNickName());
			extensionWorker.setUserId(userId);
			extensionWorker.setStatus("1");
			extensionWorker.setCreateTime(new Date());
			extensionWorker.setExtensionWorker("1");
			extensionService.save(extensionWorker);
		}else{
			String status = worker.getStatus();
			return ResponseEntity.ok(status);
		}

		return ResponseEntity.ok(result);
	}

}
